package com.ophiux.wechat.cmnative;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ophiux.wechat.cmnative.model.Native1ReturnModel;
import com.ophiux.wechat.model.SP_UnifiedOrderRequest;
import com.ophiux.wechat.model.UnifiedOrderResponse;
import com.ophiux.wechat.utils.CommonUtil;
import com.ophiux.wechat.utils.StringUtil;
import com.ophiux.wechat.utils.WeChatPayUtil;
import com.ophiux.wechat.utils.WeChatSignUtil;
import com.ophiux.wechat.utils.XmlUtil;

/**
 * 接受回调的openid和product_id
 * 样例
 * <xml><appid><![CDATA[wx7ffdd8b451235141]]></appid>
<openid><![CDATA[oo8OhwpMS5advZp5wthJO5ydey74]]></openid>
<mch_id><![CDATA[1367185002]]></mch_id>
<is_subscribe><![CDATA[N]]></is_subscribe>
<nonce_str><![CDATA[LazlXRym97jcJ9hQ]]></nonce_str>
<product_id><![CDATA[test2016-12-22-saoma-fuwushang]]></product_id>
<sign><![CDATA[62D01BB8C1F36898F79589DFE3702999]]></sign>
</xml>
 */
public class Native1CallBackServlet extends HttpServlet{

	
	private static Logger logger = LoggerFactory.getLogger(Native1CallBackServlet.class);

	/**
	 * 返回状态码
	 */
	private String RETURN_SUCCESS = "SUCCESS";
	private String RETURN_FAIL = "FAIL";
	
	/**
	 * 业务结果
	 */
	private String RESULT_SUCCESS = "SUCCESS";
	private String RESULT_FAIL = "FAIL";
	
	
	/**
	 * 服务商基本配置信息
	 * 暂时配置为重庆奥菲科服务商信息
	 */
	private static String _appid = "wx7ffdd8b451235141";
	private static String _appsecret = "dc3f53eda7e0015643e1280572ac1464";
	private static String _api_key = "1ids5eohkq5wcb8sq7qievtp9fs8juyz";
	private static String _mch_id = "1367185002";
	private static String _sub_mch_id = "1394076602";
	
	private static String _sub_appid = "wx84f6558264b003c9";
	
	/**
	 * 服务器外网IP
	 */
	private static String Spbill_create_ip = "192.168.1.10";
	/**
	 * 支付类型
	 */
	private static String Trade_type = "NATIVE";
	
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String product_id = "";
		String appid = _appid;
		String openid = "";
		String mch_id = _mch_id;
		String is_subscribe = "";
		String nonce_str = "";
		String sign = "";
		
		logger.info("---进入扫码支付回调---");
		/**
		 * 从微信扫码支付回调获取参数
		 */
//		ServletInputStream in = null;
//		try {
//			  in = request.getInputStream();
//		} catch (IOException e) {
//			e.printStackTrace();
//			logger.error("APP支付获取Req微信支付通知xml错误"+e.getLocalizedMessage());
//		}
//		/**
//		 * 将文件流转换为xml字符串
//		 */
//		String xmlStrReq = StringUtil.inputStream2String(in);
	 	String xmlStrReq = request.getParameter("name");
		logger.info("扫码支付回调参数:"+xmlStrReq);
		
		XmlUtil xmlUtil = new XmlUtil();
		/**
		 * 获取XML中的节点
		 */
	    product_id = xmlUtil.getValue(xmlStrReq, "product_id");
	    appid = xmlUtil.getValue(xmlStrReq, "appid");
	    openid = xmlUtil.getValue(xmlStrReq, "openid");
	    mch_id = xmlUtil.getValue(xmlStrReq, "mch_id");
	    is_subscribe = xmlUtil.getValue(xmlStrReq, "is_subscribe");
	    nonce_str = xmlUtil.getValue(xmlStrReq, "nonce_str");
	    sign = xmlUtil.getValue(xmlStrReq, "sign");
		
	    /**
	     * 从product_id中拆分出支付相关信息
	     * 商家自己拼接的
	     * 待实现......
	     */
	    
		logger.info("---扫码支付开始统一下单---");
		
		/**
		 * 生成预支付下单请求实体
		 */
 	
		String money = "1";
		String notifyUrl = "http://wechatpay.ophiux.com/OphiuxWeChatPayPlatformbuild/weChatPay";
		
		 SP_UnifiedOrderRequest sp_unifiedOrderRequest = new SP_UnifiedOrderRequest();
		 sp_unifiedOrderRequest.setAppid(appid);
		 sp_unifiedOrderRequest.setSub_appid(_sub_appid);
		 sp_unifiedOrderRequest.setMch_id(mch_id);
		 sp_unifiedOrderRequest.setSub_mch_id(_sub_mch_id);
		 sp_unifiedOrderRequest.setNonce_str(CommonUtil.getNonceStr());
		 //预约挂号/门诊支付
		 sp_unifiedOrderRequest.setBody("reg");
		 sp_unifiedOrderRequest.setAttach("");
		 sp_unifiedOrderRequest.setOut_trade_no(product_id);
		 sp_unifiedOrderRequest.setProduct_id(product_id);
		 sp_unifiedOrderRequest.setTotal_fee(CommonUtil.getMoney(money));
		 sp_unifiedOrderRequest.setSpbill_create_ip(Spbill_create_ip);
		 sp_unifiedOrderRequest.setNotify_url(notifyUrl);
		 sp_unifiedOrderRequest.setTrade_type(Trade_type);
		 
		/**
		 * 调用微信普通商户统一下单
		 */
		 UnifiedOrderResponse unifiedOrder = WeChatPayUtil.Native_UnifiedOrder(sp_unifiedOrderRequest, _api_key) ;
		 
		 logger.info("普通商户-扫码支付-模式一，下单结果:"+unifiedOrder.toString());
		 
		 if(unifiedOrder == null){
			 response.getWriter().write("");
		 }
		 
		 /**
		  * 构造扫码支付返回/响应参数
		  */
		 Native1ReturnModel returnModel = new Native1ReturnModel();
		 returnModel.setAppid(appid);
		 returnModel.setErr_code_des("");
		 returnModel.setMch_id(mch_id);
		 returnModel.setNonce_str(CommonUtil.getNonceStr());
		 returnModel.setPrepay_id(unifiedOrder.getPrepay_id());
		 
		 if(unifiedOrder.getError_code().equals("200")){
			 /**
			  * 下单成功
			  */
			 returnModel.setResult_code(RESULT_SUCCESS);
		 }else{
			 /**
			  * 失败
			  */
			 returnModel.setResult_code(unifiedOrder.getError_code());
			 returnModel.setErr_code_des(unifiedOrder.getError_msg());
		 }
		 returnModel.setReturn_code(RETURN_SUCCESS);
		 returnModel.setReturn_msg("");
		 
		 /*
		  * 签名
		  */
		 String returnSign = WeChatSignUtil.getInstance(_api_key)
				 .createSign(returnModel.toSortMap());
		 returnModel.setSign(returnSign);
		 
		 /**
		  * 生成返回的xml数据字符串
		  */
		 String returnxmlMsg = XmlUtil.getInstance().mapToXml(returnModel.toMap());
		 logger.info("普通商户-扫码支付-模式一，响应结果:"+returnxmlMsg);
//		 ObjectMapper obj=new ObjectMapper();
//		 String res  = obj.writeValueAsString(unifiedOrder);
//		 
//		 System.out.println(returnxmlMsg);
		 response.getWriter().write(returnxmlMsg);
		
	}
	
	
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
	
}
